package net.cyue.android.js.module;

import androidx.annotation.NonNull;

import net.cyue.android.Util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.wragony.android.jsbridge.module.JSBridgeMethod;
import com.wragony.android.jsbridge.module.JsModule;
import com.wragony.android.jsbridge.module.datatype.JBCallback;
import com.wragony.android.jsbridge.module.datatype.JBMap;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;


public class HTTPJSModule extends JsModule
{
    private Headers headers = null;

    @Override
    public String getModuleName() {
        return "HTTP";
    }

    @JSBridgeMethod
    public void setHeaders(JBMap map)
    {
        String[] keys = map.keySet().toArray(new String[0]);
        Headers.Builder builder = new Headers.Builder();
        for(String k : keys)
        {
            builder.add(k, map.get(k).toString());
        }
        this.headers = builder.build();
    }


    @JSBridgeMethod
    public void ajaxJSON(JBMap map)
    {
        try {
            String method = map.getString("method");
            if (method == null)
                method = "POST";

            String url = map.getString("url");
            JBCallback success = map.getCallback("success");
            JBCallback failed = map.getCallback("failed");

            RequestBody requestBody = RequestBody.create(
                    "{}",
                    MediaType.parse("application/json;charset=utf-8")
                );
            JBMap data = map.getJBMap("data");
            if (data != null)
            {
                Set<String> keySet = data.keySet();
                JSONObject jsonObject = new JSONObject();
                for (String k : keySet)
                {
                    jsonObject.put(k, data.get(k));
                }
                requestBody = RequestBody.create(
                    jsonObject.toString(),
                    MediaType.parse("application/json;charset=utf-8")
                );
            }

            Util.httpRequest(
                method,
                url,
                this.headers,
                requestBody,
                new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        if (failed != null)
                            failed.apply(e.getMessage());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (success != null && response.body() != null) {
                            String jsonString = response.body().string();
                            String contentType = response.header("Content-Type");
                            if (contentType != null && contentType.contains("application/json")) {
                                ObjectMapper mapper = new ObjectMapper();
                                String json = mapper.readTree(jsonString).toString();
                                success.apply(json);
                            } else {
                                success.apply(jsonString.replaceAll("\r|\n|\t", ""));
                            }
                        }
                    }
                }
            );
        } catch (NullPointerException | JSONException e) {
            TipDialog.show(e.getMessage());
        }

    }


    @JSBridgeMethod
    public void ajaxForm(JBMap map)
    {
        String method = map.getString("method");
        if (method == null)
            method = "GET";

        StringBuilder url = new StringBuilder(map.getString("url"));
        JBCallback success = map.getCallback("success");
        JBCallback failed = map.getCallback("failed");

        FormBody.Builder builder = new FormBody.Builder();
        RequestBody requestBody = null;
        JBMap data = map.getJBMap("data");

        if (data != null) {
            Set<String> keySet = data.keySet();
            if (method.equals("GET") || method.equals("get"))
            {
                url.append("?");
                for(String key : keySet)
                {
                    url.append(key).append("=").append(data.get(key).toString());
                }
            }
            else {
                for(String key : keySet)
                {
                    builder.add(key, data.get(key).toString());
                }
                requestBody = builder.build();
            }
        }

        Util.httpRequest(
            method,
            url.toString(),
            this.headers,
            requestBody,
            new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    if (failed != null)
                        failed.apply(e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    if (success != null && response.body() != null) {
                        String jsonString = response.body().string();
                        String contentType = response.header("Content-Type");
                        if (contentType != null && contentType.contains("application/json")) {
                            ObjectMapper mapper = new ObjectMapper();
                            String json = mapper.readTree(jsonString).toString();
                            success.apply(json);
                        } else {
                            success.apply(jsonString.replaceAll("\r|\n|\t", ""));
                        }
                    }
                }
            }
        );
    }



}

